package com.abkj.platform.tail.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.abkj.platform.base.dao.warp.SQLType;
import com.abkj.platform.base.util.PageResult;
import com.abkj.platform.tail.domain.JcUser;
import com.abkj.platform.tail.domain.JcUserLog;
import com.abkj.platform.tail.service.AlarmService;
import com.abkj.platform.tail.service.IAlertService;
import com.abkj.platform.tail.service.ISMSService;
import com.abkj.platform.tail.util.Base64Util;
import com.abkj.platform.tail.util.JsonUtils;

@Controller
@RequestMapping({ "system" })
public class SystemController extends BaseController {
	
	@Autowired
	private ISMSService smsService;
	@Autowired
	private IAlertService alertService;
	
	@RequestMapping({ "/user_create" })
	public String userCreate(ModelMap model, @RequestParam(value = "id", defaultValue = "-1") int userId) {
		return "/system/user_add";
	}

	@RequestMapping({ "/user_edit" })
	public String userEdit(ModelMap model, @RequestParam(value = "id", defaultValue = "-1") int userId) {
		if (userId != -1) {
			JcUser jcUser = (JcUser) this.baseService.loadObjectById(JcUser.class, userId);
			model.put("user", jcUser);
		}

		return "/system/user_update";
	}

	@RequestMapping({ "/user_saveOrupdate" })
	public String userSaveOrUpdate(HttpServletRequest request, ModelMap model, JcUser jcUser) {
		Integer id = jcUser.getId();
		String password = Base64Util.encodePwd(jcUser.getPassword() == null ? "" : jcUser.getPassword());
		jcUser.setPassword(password);
		if ((id != null) && (id.intValue() > 0)) {
			this.baseService.updateObject(jcUser, "username,name,type,mobile,comment,code");
		} else {
			jcUser.setCreatetime(new Date());
			jcUser.setLasttime(null);
			this.baseService.insertObject(jcUser);
		}
		return "redirect:user";
	}

	@RequestMapping({ "/user" })
	public String userPageList(ModelMap model, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
			@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "name", defaultValue = "") String name) {
		String countsql = "select count(*) as count from jcuser where 1=1 ";
		String sql = "select * from jcuser where 1=1 ";
		if (StringUtils.isNotEmpty(username)) {
			countsql = countsql + "and username like '%" + username + "%' ";
			sql = sql + "and username like '%" + username + "%' ";
		}
		if (StringUtils.isNotEmpty(name)) {
			countsql = countsql + "and name like '%" + name + "%' ";
			sql = sql + "and name like '%" + name + "%' ";
		}
		PageResult ss = this.baseService.findByPage(JcUser.class, countsql, sql, pageNo, pageSize);
		model.put("username", username);
		model.put("name", name);
		model.put("pr", ss);
		return "/system/user";
	}

	@RequestMapping({ "/user_delete" })
	public String userDelete(HttpServletRequest request, @RequestParam("id") int id, @RequestParam("state") int state) {
		this.baseService.excuteBySql(SQLType.UPDATE, "update jcuser set state = " + state + " where id = " + id);
		if (state == 1)
			createJcUserLog(request, "用户管理", "启用ID为 " + id + " 的用户！");
		else {
			createJcUserLog(request, "用户管理", "禁用ID为 " + id + " 的用户！");
		}
		return "redirect:user";
	}

	@RequestMapping({ "/userlog" })
	public String userlog(ModelMap model, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(value = "pageSize", defaultValue = "12") int pageSize,
			@RequestParam(value = "uid", defaultValue = "0") int uid) {
		String countsql = "select count(*) as count from jcuserlog where 1=1 ";
		String sql = "select a.id as id,u.username as username,u.name as name,a.createtime as createtime,a.content as content,a.type as type from jcuserlog a,jcuser u where a.uid = u.id ";
		if (uid > 0) {
			countsql = countsql + "and uid = " + uid;
			sql = sql + "and uid = " + uid;
		}
		PageResult pr = this.baseService.findByPage(JcUserLog.class, countsql, sql, pageNo, pageSize);
		List users = this.baseService.findAllObjects(JcUser.class);
		model.put("uid", Integer.valueOf(uid));
		model.put("pr", pr);
		model.put("users", users);
		return "/system/userlog";
	}

	@RequestMapping(value = { "/check_username" }, produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String checkUserNameRepeat(@RequestParam(value = "username", defaultValue = "") String username) {
		List m = this.baseService.findBySql("select id from jcuser where username = '" + username + "'");
		return String.valueOf(m.size() == 0);
	}

	@RequestMapping(value = { "/saveMapFile" }, produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String yuan_saveOrUpdateFile(HttpServletRequest req,
			@RequestParam("attach") CommonsMultipartFile attachment) {
		if ((attachment != null) && (!attachment.isEmpty())) {
			System.out.println(attachment);
			File doc = generateFile("map.jpg", req);
			try {
				FileUtils.copyInputStreamToFile(attachment.getInputStream(), doc);
			} catch (IOException e) {
				e.printStackTrace();
				return "0";
			}
		}
		return "1";
	}

	private File generateFile(String path, HttpServletRequest req) {
		String contextPath = req.getSession().getServletContext().getRealPath("\\");
		return new File(contextPath + "\\resources\\map\\" + path);
	}
	@RequestMapping({ "/smsSetting" })
	public ModelAndView smsSetting(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("system/smsSetting");
		Map<String, Object> form = smsService.getForm();
		mv.addAllObjects(form);
		return mv;
	}
	@RequestMapping({ "/smsUpdate" })
	public String smsUpdate(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", request.getParameter("name"));
		map.put("phoneNo", request.getParameter("phoneNo"));
		map.put("msg", request.getParameter("msg"));
		map.put("able", request.getParameter("able"));
		map.put("auto", request.getParameter("auto"));
		Boolean isSuccess = smsService.update(map);
		return "redirect:smsSetting";
	}
	@RequestMapping(value = { "sendMsg" }, produces = { "text/html;charset=UTF-8" })
	@ResponseBody
	public String sendMsg(){
		Boolean isSuccess = true;
		//发送预警短信
		try {
			smsService.sendMsg(null, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			isSuccess = false;
		}
		return JsonUtils.writeObjToString(isSuccess);
	}
	@RequestMapping({ "/alertSetting" })
	public ModelAndView alertSetting(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("system/alertSetting");
		Map<String, Object> form = alertService.getForm();
		mv.addAllObjects(form);
		return mv;
	}
	@RequestMapping({ "/alertUpdate" })
	public String alertUpdate(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("minute", request.getParameter("minute"));
		map.put("able", request.getParameter("able"));
		Boolean isSuccess = alertService.update(map);
		return "redirect:alertSetting";
	}
	/*@RequestMapping({ "/user_saveOrupdate" })
	public String userSaveOrUpdate(HttpServletRequest request, ModelMap model, JcUser jcUser) {
		Integer id = jcUser.getId();
		String password = Base64Util.encodePwd(jcUser.getPassword() == null ? "" : jcUser.getPassword());
		jcUser.setPassword(password);
		if ((id != null) && (id.intValue() > 0)) {
			this.baseService.updateObject(jcUser, "username,name,type,mobile,comment,code");
		} else {
			jcUser.setCreatetime(new Date());
			jcUser.setLasttime(null);
			this.baseService.insertObject(jcUser);
		}
		return "redirect:user";
	}*/
}